﻿Global.namespace("System.Web.Page");

System.Web.Page.Home=function(config){
    config.templateFile="Home.htm?t="+ Global.random();
    System.Web.Page.Home.superclass.constructor.call(this,config);
}
Global.extend(System.Web.Page.Home,System.Core.UI.BasePage,{
    owner:null,
    friends:null,
	osUserDict:null,
    template:"<div id='{0}' class='MaxWidth'></div>",
    innerHtml:'',
    onRendered:function(){
        this.initRequest();
        
    },
    onLoading:function(){   
        if($('#home_Loading').length===0){
            Global.showLoadingMask({
                wrapper:'#'+this.id,
                id:'home_Loading'
            });
        }
    },
    initRequest:function(){
        // create the opensocial.DataRequest object.
        var request = opensocial.newDataRequest();
        // create a list of Person fields to fetch,
        // in this case, include all supported fields.
        var fields = [  
                        opensocial.Person.Field.ID,
					    opensocial.Person.Field.AGE,
					    opensocial.Person.Field.BODY_TYPE,
					    opensocial.Person.Field.BOOKS,
					    opensocial.Person.Field.CHILDREN,
					    opensocial.Person.Field.CURRENT_LOCATION,
					    opensocial.Person.Field.DATE_OF_BIRTH,
					    opensocial.Person.Field.NAME,
					    opensocial.Person.Field.NICKNAME,
					    opensocial.Person.Field.PROFILE_SONG,
					    opensocial.Person.Field.PROFILE_URL,
					    opensocial.Person.Field.RELATIONSHIP_STATUS,
					    opensocial.Person.Field.RELIGION,
					    opensocial.Person.Field.SEXUAL_ORIENTATION,
					    opensocial.Person.Field.SMOKER,
					    opensocial.Person.Field.STATUS,
					    opensocial.Person.Field.THUMBNAIL_URL,
					    opensocial.Person.Field.TV_SHOWS,
					    opensocial.Person.Field.GENDER,
					    opensocial.Person.Field.URLS
					];

	    var params = {};
	    params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = fields;
        params[opensocial.DataRequest.DataRequestFields.ESCAPE_TYPE] = opensocial.EscapeType.HTML_ESCAPE;

        var ctr=this;
	    var idspec = opensocial.newIdSpec({ "userId" : "OWNER", "groupId" : "FRIENDS" });
	    var req = opensocial.newDataRequest();
	    
	    req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.OWNER, params), "get_owner");
	    req.add(req.newFetchPeopleRequest(idspec, params), "get_friends");
        req.send(ctr.gotResponse);
    },
    gotResponse:function(response){
		System.Web.Runtime.currentUser= this.owner = response.get('get_owner').getData();
	    friends = response.get('get_friends').getData(); 
	    
		var ctr=System.Web.Page.Home.prototype;
		ctr.loadData();
    }
	,loadData:function(){
	    var ctr=this;
		var serviceURL = Config.rootServiceURL + 'GetData.axd?action=GetIDList&t='+Global.random() ;
		
	    System.Core.Handler.RequestHandler.get(
			serviceURL,
			{},
	        function(response){
	            var data=System.Core.Handler.RequestHandler.getResponseData(response);
			    var IDs = eval(StringHandler.format("({0})",data));
				
				System.Web.Runtime.userDict = new Dictionary();
			    for(var i=0 ; i<IDs.length ; i++){
					System.Web.Runtime.userDict.add(IDs[i], IDs[i]);
	            };			
				
				osUserDict = new Dictionary();
				var p = new User(owner.getField(opensocial.Person.Field.ID), owner.getDisplayName());
				osUserDict.add(p.id, p);
				
				var receiverIDList = '';
				var content = $("#content");
				var html='';
				//var ctr=this;//System.Web.Page.Home.prototype;

				for(var i=0 ; i<this.friends.array_.length ; i++){
					var person = this.friends.array_[i];
					receiverIDList += person.getField(opensocial.Person.Field.ID);
					if(i<this.friends.array_.length-1) receiverIDList += ",";
					p = new User(person.getField(opensocial.Person.Field.ID), person.getDisplayName());
					osUserDict.add(p.id, p);
					
					html += ctr.createPerson(person);
				};
				content.html(html);
				
				$('.ClickEvent').click(function(){
				    ctr.processEvent(this);
				});
				
				ctr.showGiftsLinks(receiverIDList);

                Global.hideLoadingMask('home_Loading');
                gadgets.window.adjustHeight();
				// hide the spinner and show the content now that the DOM has been populated.
				$("#content").css("display","block");
				
				// make the iframe fit the new content.
				gadgets.window.adjustHeight();
	    });
	},
	processEvent:function(item){
	    item=$('#'+item.id);
	    var action=item.attr('action');
	    var receiver=item.attr('receiver');
	    var name=item.attr('name');
	    
	    switch(action){
	        case 'sendmessage':
	            this.loadControl(System.Web.Page.SendMessage, { receiverName:name ,receiverId:receiver,isSendGift:false, wrapper: '.MasterPageWrapper',autoRender:true});
	        break;
	    case 'sendgift':
	            this.loadControl(System.Web.Page.SendMessage, { receiverName:name ,receiverId:receiver,isSendGift:true, wrapper: '.MasterPageWrapper',autoRender:true});
	        break;
	    default:
	            this.loadControl(System.Web.Page.InviteFriend, { receiverId:receiver,wrapper: '.MasterPageWrapper',autoRender:true});
	        break;
	    }
	},
	createPerson:function(person){
	    var htmlCode = 
	    "<div> \
		    <div id='headline' class='divider'><strong>{0}</strong>{4}</div> \
            <div class='float'> \
                <center class='imageLinks'> \
                    <a href=''><img src='{1}'/></a> \
               </center> \
            </div> \
            <div id='details'>{2}</div> \
            <div class='clear'></div> \
			<div id='gifts{3}' class='allGifts' style='display:none'></div> \
			<span id='loadedGifts{3}' style='display:none'>0</span>			\
        </div>";
    		
	    var dob = person.getField(opensocial.Person.Field.DATE_OF_BIRTH);
	    var gender = person.getField(opensocial.Person.Field.GENDER);

		var id = person.getField(opensocial.Person.Field.ID);
		var ctr=System.Web.Page.Home.prototype;
	    var details = StringHandler.format("{0}{1} years old<br/>{2}{3}<span id='showGiftsSpan{4}' style='display:none'><a href='#' id='showGifts{4}'></a> | </span><a onclick='return false;' id='sendInvitation{4}' receiver='{4}' action='{6}' name='{7}'  class='ClickEvent' href='#'>{5}</a> | <a class='ClickEvent'  name='{7}' onclick='return false;' id='sendMessage{4}' action='sendmessage' receiver='{4}' href='#'>Send message</a>"
					    ,gender ? gender.getDisplayValue() + "<br/>" : ""
					    ,person.getField(opensocial.Person.Field.AGE)
					    , dob ? dob.format("mmmm d, yyyy") : ""
						, ctr.remindBirthDayString(dob, gender.getDisplayValue()) + "<br/>"
					    , id
						, System.Web.Runtime.userDict.exists(id)  ? "Send gifts" : "invite friend"
						, System.Web.Runtime.userDict.exists(id)  ? "sendgift" : "sendinvitation"
						, person.getDisplayName()
					    );

        var status=person.getField("relationshipStatus");
        
	    htmlCode = StringHandler.format(htmlCode
					    ,person.getDisplayName()
					    ,person.getField(opensocial.Person.Field.THUMBNAIL_URL)
					    ,details
						,person.getField(opensocial.Person.Field.ID)
						, status && status.length>0?"<span class='Status'> - "+ status+"</span>":""
						);
    	
	    return htmlCode;
    }
	
	,remindBirthDayString:function(birthday, gender) {
		var now = new Date();
		now.setFullYear(birthday.getFullYear());
		
		if(birthday > now) {
			var day = parseFloat(birthday - now) / System.Web.Runtime.milisecondPerDay;
			if(day < Config.timeToRemind) {
				day = Math.ceil(day);
				return StringHandler.format("<span style='color:red'> (Only {0} day{1} to {2} birthday, give {3} a gift?)</span>"
					, day
					, day > 1 ? "s" : ""
					, gender == 'female' ? "her" : "his"
					, gender == 'female' ? "her" : "him");
			}
		}
		return "";
	}
	,showGiftsLinks:function(receiverIDList){
		var ctr=this;
		var serviceURL =StringHandler.format(
		    '{0}GetData.axd?action=GetTotalPresentsList&t={1}&receiverIDList={2}',
		    Config.rootServiceURL,
		    Global.random(),
		    receiverIDList
		);
		
	    System.Core.Handler.RequestHandler.get(
			serviceURL,
			{},
	        function(response){
	            var data=System.Core.Handler.RequestHandler.getResponseData(response);
			    var totalNumberPresents = eval(StringHandler.format("({0})",data));

			    for(var i=0 ; i<totalNumberPresents.length ; i++){
			        var totalNumberPresent = totalNumberPresents[i];
			        if(totalNumberPresent.TotalNumber > 0) {
						var id = totalNumberPresent.ReceiverID;
						var showGiftsID="#showGifts"+id;
						var showGiftLink = $(showGiftsID);
						showGiftLink.html("Show gifts(" + totalNumberPresent.TotalNumber + ")");
						showGiftLink.attr("href", "javascript:void()");
						showGiftLink.tooltip({ 
							width: 200,
							track: true,
							delay: 0, 
							showURL: false, 
							bodyHandler: function() { 
								var gId = this.id.substring(9);
								if($('#loadedGifts' + gId).html()=='2') {
									var gifts = $('#gifts' + gId);
									return $("<div class='GiftToolTip' id='giftListOnToolTip"+gId+"'/>").html(gifts.html());
								}
								
								if($('#loadedGifts' + gId).html()=='0') {
									ctr.loadGifts(gId);
								}
								var imgSrc='http://x.myspacecdn.com/modules/common/static/img/loadercircles.gif';
								var htmlLoading="<div id='giftListOnToolTip"+gId+"' class='GiftToolTip'><center><img src='"+imgSrc+"' /></center></div>";
								
								return $(htmlLoading);
							} 
						});
						
						var showGiftsSpanID="#showGiftsSpan"+id;
						$(showGiftsSpanID).show();
	                }
	            };			
	    });
	},
	loadGifts:function(id){
		if($('#loadedGifts' + id).html()=='0') {
			$('#loadedGifts' + id).html('1');
			var serviceURL = Config.rootServiceURL +'GetData.axd?action=GetPresentsListByReceiverId&t='+Global.random()+"&receiverID="+id;
			System.Core.Handler.RequestHandler.get(
				serviceURL,
				{},
				function(response){
					var data=System.Core.Handler.RequestHandler.getResponseData(response);
					var presents = eval(StringHandler.format("({0})",data));
					
					var htmlCode = 
					"	<div class='Gifts'> \
							<div id='headline' class='divider'><strong>{0}</strong></div> \
							<div class='float'> \
								<center class='imageLinks'> \
									<a href=''><img src='{1}'/></a> \
							   </center> \
							</div> \
							<div id='details'>{2}</div> \
							<div class='clear'></div> \
						</div> \
						";
					var gifts = $('#gifts' + id);
					var html = '';
					for(var i=0 ; i<presents.length ; i++){
						var present = presents[i];				
						var presentURL = StringHandler.format("{0}Gifts/{1}",Config.imageUrl,present.GiftImage);
				
						var details = StringHandler.format("<strong>Sender:</strong>{0}<strong>Message:</strong>{1}"
								,(osUserDict.exists(present.SenderID) ? osUserDict.getVal(present.SenderID).name : "Opp!, he/she has not been signed up, send him/her an invitation email?" )+ "<br/>"
								,present.Message + "<br/>"
							);
			
						html += StringHandler.format(htmlCode
							,present.GiftName
							,presentURL
							,details
							);	
					};	
					$('#loadedGifts' + id).html('2');
					$('#giftListOnToolTip' + id).html(html);
					gifts.html(html);		
			});
		}
	}
});